package vtt.android.dapanhc;

import vtt.android.dapanhc.activities.TopActivity;
import vtt.android.dapanhc.utils.VttAlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

public class MyBroadcastReceiver extends BroadcastReceiver {

	Context mContext;

	@Override
	public void onReceive(Context ctx, Intent intent) {
		mContext = ctx;
		SharedPreferences sharedPreferences = ctx.getSharedPreferences(Constants.SHARE_PREFERENCE_NAME, Context.MODE_PRIVATE);
		if(intent != null && Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())){
			boolean isStartAlarm = sharedPreferences.getBoolean(Constants.KEY_IS_START_ALARM, false);
			if(!isStartAlarm){
				int hour = sharedPreferences.getInt(Constants.SHARE_KEY_NOTICE_HOUR, 0);
				// set repeat alarm everyday for showing notification
				VttAlarmManager.startAlarmEveryday(mContext, hour, MyBroadcastReceiver.class);
				sharedPreferences.edit().putBoolean(Constants.KEY_IS_START_ALARM, true).commit();
				//Log.d("TEST", "VTT>>> onReceive return");
				return;
			}
		}
		
		// check whether show notification
		boolean isShowNotice = sharedPreferences.getBoolean(Constants.SHARE_KEY_SHOW_NOTICE, true);
		Log.i("TEST", "VTT>>> onReceive isShowNotice " + isShowNotice);
		if (isShowNotice) {
			showNotification();
		}
	}

	@SuppressWarnings("deprecation")
	private void showNotification() {
		NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

		Intent intent1 = new Intent(mContext.getApplicationContext(), TopActivity.class);

		Notification notification = new Notification(R.drawable.ic_launcher, mContext.getString(R.string.app_name), System.currentTimeMillis());
		intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

		PendingIntent pIntent = PendingIntent.getActivity(mContext, 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), mContext.getString(R.string.msg_alert_new_lesson), pIntent);

		notificationManager.notify(0, notification);
	}

}
